<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="脚本标识" prop="scriptKey">
        <el-input
          v-model="queryParams.scriptKey"
          placeholder="请输入脚本标识"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="脚本名称" prop="scriptName">
        <el-input
          v-model="queryParams.scriptName"
          placeholder="请输入脚本名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属产品" prop="productId">
        <el-select v-model="queryParams.productId" placeholder="请选择所属产品" clearable size="small">
          <el-option
            v-for="item in productOptions"
            :key="item.id"
            :label="item.productName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['iot:script:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['iot:script:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="scriptList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="脚本名称" align="center" prop="scriptName" />
      <el-table-column label="所属产品" align="center" prop="productName" />
      <el-table-column label="脚本标识" align="center" prop="id" />
      <el-table-column label="脚本事件" align="center" prop="scriptEvent">
        <template slot-scope="scope">
          <span>{{ getScriptEventLabel(scope.row.scriptEvent) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="脚本动作" align="center" prop="scriptAction">
        <template slot-scope="scope">
          <span>{{ getScriptActionLabel(scope.row.scriptAction) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="脚本语言" align="center" prop="scriptLanguage" />
      <el-table-column label="状态" align="center" prop="isEnabled">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isEnabled == 1 ? 'success' : 'danger'">
            {{ scope.row.isEnabled == 1 ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="执行顺序" align="center" prop="scriptOrder" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['iot:script:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iot:script:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改规则脚本对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="脚本名称" prop="scriptName">
              <el-input v-model="form.scriptName" placeholder="请输入脚本名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行顺序" prop="scriptOrder">
              <el-input-number v-model="form.scriptOrder" :min="1" :max="999" controls-position="right"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="脚本事件" prop="scriptEvent">
              <el-select v-model="form.scriptEvent" placeholder="请选择脚本事件" style="width: 100%">
                <el-option label="属性上报" :value="1"/>
                <el-option label="设备上线" :value="2"/> 
                <el-option label="设备离线" :value="3"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="脚本动作" prop="scriptAction">
              <el-select v-model="form.scriptAction" placeholder="请选择脚本动作" style="width: 100%">
                <el-option label="消息重发" :value="1"/>
                <el-option label="告警通知" :value="2"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="脚本状态" prop="isEnabled">
              <el-switch v-model="form.isEnabled" active-value="1" inactive-value="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属产品" prop="productId" class="product-select">
              <el-input v-model="form.productName" placeholder="产品名称" readonly>
                <el-button slot="append" @click="openProductSelect">选择</el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="脚本内容" prop="scriptData">
              <el-input
                v-model="form.scriptData"
                type="textarea"
                :rows="10"
                placeholder="请输入脚本内容"
              />
              <el-button type="primary" size="mini" @click="handleValidateScript" style="margin-top: 10px">验证脚本</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 产品选择对话框 -->
    <el-dialog title="选择产品" :visible.sync="productDialogVisible" width="800px" append-to-body>
      <div class="product-search">
        <span class="label">产品名称</span>
        <el-input
          v-model="productQueryParams.productName"
          placeholder="请输入产品名称"
          clearable
          style="width: 300px"
          @keyup.enter.native="handleProductQuery"
        >
          <el-button slot="append" icon="el-icon-search" @click="handleProductQuery">搜索</el-button>
        </el-input>
        <el-button icon="el-icon-refresh" @click="resetProductQuery">重置</el-button>
      </div>

      <el-table v-loading="productLoading" :data="productOptions" @selection-change="handleProductSelectionChange" highlight-current-row>
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="产品名称" align="center" prop="productName"/>
        <el-table-column label="产品类型" align="center" prop="deviceType"/>
        <el-table-column label="传输协议" align="center" prop="transProtocol"/>
        <el-table-column label="启动授权" align="center" prop="authFlag">
          <template slot-scope="scope">
            {{ scope.row.authFlag ? 'true' : 'false' }}
          </template>
        </el-table-column>
        <el-table-column label="认证方式" align="center" prop="authMode"/>
        <el-table-column label="产品编号" align="center" prop="productCode"/>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
      </el-table>

      <div class="pagination-container">
        <span class="total-text">共 {{ productTotal }} 条</span>
        <el-select v-model="productQueryParams.pageSize" size="mini" style="width: 120px">
          <el-option label="10条/页" value="10"/>
          <el-option label="20条/页" value="20"/>
          <el-option label="30条/页" value="30"/>
        </el-select>
        <el-pagination
          :current-page.sync="productQueryParams.pageNum"
          :page-size="productQueryParams.pageSize"
          :total="productTotal"
          layout="prev, pager, next"
          @current-change="handleProductQuery"
        />
        <span class="page-text">前往 <el-input v-model="productQueryParams.pageNum" size="mini" style="width: 60px"/> 页</span>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmProductSelect">确 定</el-button>
        <el-button @click="cancelProductSelect">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listScript, getScript, delScript, addScript, updateScript, validateScript } from "@/api/iot/script";
import { listProduct } from "@/api/iot/product";
import DictTag from "@/components/DictTag";

export default {
  name: "Script",
  components: {
    DictTag
  },
  dicts: ['iot_device_type', 'iot_trans_protocol', 'iot_script_event', 'iot_script_action'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 规则脚本表格数据
      scriptList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 产品选择弹出层
      productDialogVisible: false,
      // 产品选项
      productOptions: [],
      // 选中的产品
      selectedProduct: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        scriptKey: undefined,
        scriptName: undefined,
        productId: undefined,
        productName: undefined
      },
      // 表单参数
      form: {
        id: undefined,
        scriptName: undefined,
        productId: undefined,
        productName: undefined,
        scriptId: undefined,
        scriptEvent: undefined,
        scriptAction: undefined,
        scriptData: undefined,
        scriptOrder: 1,
        isEnabled: "0",
        scriptLanguage: undefined,
        scriptType: undefined,
        scriptUsage: undefined
      },
      // 表单校验
      rules: {
        scriptName: [
          { required: true, message: "脚本名称不能为空", trigger: "blur" }
        ],
        productId: [
          { required: true, message: "所属产品不能为空", trigger: "change" }
        ],
        scriptEvent: [
          { required: true, message: "脚本事件不能为空", trigger: "change" }
        ],
        scriptAction: [
          { required: true, message: "脚本动作不能为空", trigger: "change" }
        ],
        scriptData: [
          { required: true, message: "脚本内容不能为空", trigger: "blur" }
        ]
      },
      // 产品选择相关
      productLoading: false,
      productTotal: 0,
      productQueryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: undefined
      },
      // 脚本事件选项
      scriptEventOptions: [
        { label: "属性上报", value: "1" },
        { label: "设备上线", value: "2" },
        { label: "设备离线", value: "3" }
      ],
      // 脚本动作选项
      scriptActionOptions: [
        { label: "消息重发", value: "1" },
        { label: "告警通知", value: "2" }
      ]
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询规则脚本列表 */
    getList() {
      this.loading = true;
      listScript(this.queryParams).then(response => {
        this.scriptList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        scriptName: undefined,
        productId: undefined,
        productName: undefined,
        scriptId: undefined,
        scriptEvent: undefined,
        scriptAction: undefined,
        scriptData: undefined,
        scriptOrder: 1,
        isEnabled: "0",
        scriptLanguage: undefined,
        scriptType: undefined,
        scriptUsage: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加规则脚本";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0]
      getScript(id).then(response => {
        this.form = response.data;
        this.form.isEnabled = this.form.isEnabled.toString();
        this.open = true;
        this.title = "修改规则脚本";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 添加调试日志
          console.log("提交的表单数据:", this.form);
          
          // 创建提交的数据对象，转换isEnabled为数字
          const submitData = {
            ...this.form,
            isEnabled: parseInt(this.form.isEnabled)
          };
          
          if (this.form.id) {
            updateScript(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error("修改请求错误:", error);
            });
          } else {
            addScript(submitData).then(response => {
              // 添加调试日志
              console.log("新增响应数据:", response);
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error("新增请求错误:", error);
            });
          }
        } else {
          console.log("表单验证失败");
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除规则脚本编号为"' + ids + '"的数据项？').then(function() {
        return delScript(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 打开产品选择框 */
    openProductSelect() {
      this.productDialogVisible = true;
      this.getProductOptions();
    },
    /** 产品查询 */
    handleProductQuery() {
      this.getProductOptions();
    },
    /** 重置产品查询 */
    resetProductQuery() {
      this.resetForm("queryForm");
      this.handleProductQuery();
    },
    /** 获取产品选项 */
    getProductOptions() {
      this.productLoading = true;
      listProduct(this.productQueryParams).then(response => {
        this.productOptions = response.rows;
        this.productTotal = response.total;
        this.productLoading = false;
      });
    },
    /** 产品选择框选中数据 */
    handleProductSelectionChange(selection) {
      this.selectedProduct = selection.length ? selection[0] : null;
    },
    /** 确认选择产品 */
    confirmProductSelect() {
      if (this.selectedProduct) {
        this.form.productId = this.selectedProduct.id;
        this.form.productName = this.selectedProduct.productName;
        this.productDialogVisible = false;
        this.selectedProduct = null; // 清空选择，避免影响下次选择
      } else {
        this.$modal.msgError("请选择一个产品");
      }
    },
    /** 取消选择产品 */
    cancelProductSelect() {
      this.selectedProduct = null;
      this.productDialogVisible = false;
    },
    /** 验证脚本内容 */
    handleValidateScript() {
      if (!this.form.scriptData) {
        this.$message.warning("请先输入脚本内容");
        return;
      }
      validateScript({
        scriptId: this.form.scriptId || '',
        scriptData: this.form.scriptData,
        scriptLanguage: this.form.scriptLanguage || 'groovy'
      }).then(response => {
        this.$modal.msgSuccess("脚本验证通过");
      }).catch(error => {
        console.error('Script validation failed:', error);
        this.$modal.msgError(error.message || "脚本验证失败");
      });
    },
    /** 获取脚本事件显示标签 */
    getScriptEventLabel(value) {
      const option = this.scriptEventOptions.find(opt => opt.value == value);
      return option ? option.label : value;
    },
    /** 获取脚本动作显示标签 */
    getScriptActionLabel(value) {
      const option = this.scriptActionOptions.find(opt => opt.value == value);
      return option ? option.label : value;
    }
  }
};
</script>

<style scoped>
.top-right-btn {
  position: relative;
  text-align: right;
}
.product-select .el-input-group__append {
  background-color: #fff;
}
.product-search {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}
.product-search .label {
  margin-right: 10px;
}
.pagination-container {
  margin-top: 20px;
  padding: 10px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
.pagination-container .total-text {
  margin-right: 10px;
}
.pagination-container .page-text {
  margin-left: 10px;
  display: flex;
  align-items: center;
}
.pagination-container .page-text .el-input {
  margin: 0 5px;
}
.pagination-container .el-pagination {
  margin: 0 10px;
}
</style> 